package com.junjie.blibli.api;

import com.alibaba.fastjson.JSONObject;
import com.junjie.blibli.Entity.User;
import com.junjie.blibli.Entity.UserInfo;
import com.junjie.blibli.Support.UserSupport;
import com.junjie.blibli.result.JsonResponse;
import com.junjie.blibli.result.PageResult;
import com.junjie.blibli.service.UserFollowingService;
import com.junjie.blibli.service.UserService;
import com.junjie.blibli.util.RSAUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.Map;

@RestController
@Validated
public class UserApi {
    @Autowired
    private UserService userService;

    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserFollowingService userFollowingService;

    //获取公钥的接口，这里前端要先拿到公钥才可以加密
    @GetMapping("/rsa-pks")
    public JsonResponse<String> getRsaPublicKey(){
        String publicKey = RSAUtil.getPublicKeyStr();
        return new JsonResponse<>(publicKey);
    }

    //注册接口
    @PostMapping("/users")
    public JsonResponse<String> addUser(@RequestBody @Valid User user){
        userService.addUser(user);
        return JsonResponse.success();
    }

    //用户登录，获取token
    @PostMapping("/user-tokens")
    public JsonResponse<String> login(@RequestBody User user) throws Exception{
        String token = userService.login(user);
        return JsonResponse.success(token);
    }

    //双令牌登录接口（建议改成拦截器）
    @PostMapping("/user-dts")
    public JsonResponse<Map<String,Object>> loginForDts(@RequestBody User user) throws Exception{
        Map<String,Object> map = userService.loginForDts(user);
        return new JsonResponse<>(map);
    }

    //获取当前用户详情信息
    @GetMapping("/users")
    public JsonResponse<User> getUserInfo(){
        Long userId = userSupport.getCurrentUserId();
        User user = userService.getUserInfo(userId);
        return new JsonResponse<>(user);
    }

    //用户登出
    @DeleteMapping("/refresh-tokens")
    public JsonResponse<String> logout(HttpServletRequest request){
        //TODO refreshToken和userId感觉可以封装在同一个ThreadLocal中
        String refreshToken = request.getHeader("refreshToken");
        Long userId = userSupport.getCurrentUserId();
        userService.logout(refreshToken,userId);
        return JsonResponse.success();
    }

    //刷新token
    @PostMapping("/access-tokens")
    public JsonResponse<String> refreshAccessToken(HttpServletRequest request) throws Exception {
        String refreshToken = request.getHeader("refreshToken");
        String accessToken = userService.refreshAccessToken(refreshToken);
        return new JsonResponse<>(accessToken);
    }

    //修改用户基础信息
    @PutMapping("/user-infos")
    public JsonResponse<String> updateUserInfos(@RequestBody UserInfo userInfo){
        Long userId = userSupport.getCurrentUserId();
        userInfo.setUserId(userId);
        userService.updateUserInfos(userInfo);
        return null;
    }

    //搜索用户列表
    @GetMapping("/user-infos")
    public JsonResponse<PageResult<UserInfo>> pageListUserInfos(@RequestParam Integer no, Integer size, String nick){
        Long userId = userSupport.getCurrentUserId();
        //这里可以直接使用JSONObject代替map集合，因为Map拿出来可能需要强转，麻烦
        JSONObject params = new JSONObject();
        params.put("no",no);
        params.put("size",size);
        params.put("nick",nick);
        params.put("userId",userId);
        //分页查询出用户具体信息
        PageResult<UserInfo> result = userService.pageListUserInfos(params);
        //用户数量>0，再做具体操作，要检查与这些用户的关系，看看是否关注过了
        if(result.getTotal()>0){
            List<UserInfo> checkUserInfoList = userFollowingService.checkFollowingState(result.getList(),userId);
            result.setList(checkUserInfoList);
        }
        return new JsonResponse<>(result);
    }

}
